package com.kukudb.asaproject.utils;


import com.kukudb.asaproject.pojo.User;
import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtils {

    static Logger logger = LoggerFactory.getLogger(JWTUtils.class);

    public static final String SECRET = "kukudb";

    public static String createToker(User user) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getUserId());

        JwtBuilder builder = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .setClaims(claims)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 7));
        String token = builder.compact();
        return token;
    }

    public static Map<String,Object> checkToken(String token) {
        try {
            Jwt jwt = Jwts.parser().setSigningKey(SECRET).parse(token);
//            logger.info("token 验证成功");
            return (Map<String,Object>) jwt.getBody();
        } catch (Exception e) {
            logger.error("token 验证失败", e);
            e.printStackTrace();
        }
        return null;
    }

    public static Integer getSessionUserId(HttpSession session) {
        try {
            return (Integer)JWTUtils.checkToken(session.getAttribute("token").toString()).get("userId");
        }catch (Exception e) {
            logger.error("获取用户ID失败", e);
            throw  new IllegalArgumentException("获取失败，未登录");
        }

    }

    public static void main(String[] args) {
        User user = new User();
        user.setUserId(1);
        user.setUserName("admin");
        user.setPassword("123456");
        user.setEmail("admin@qq.com");
        String token = createToker(user);
        System.out.println(token);
        Map<String,Object> map = checkToken(token);
        System.out.println(map);

    }
}
